package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.annotation.RequiresPermissionsDesc;
import com.qf.pojo.DtsBrand;
import com.qf.pojo.DtsCategory;
import com.qf.pojo.DtsGoods;
import com.qf.service.*;
import com.qf.util.AuthSupport;
import com.qf.util.ResponseUtil;
import com.qf.vo.CatVo;
import com.qf.vo.GoodsAllinone;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @auther Administrator
 * @date 2023/2/23 21:24
 */
@RestController
@CrossOrigin("*")
@RequestMapping("/admin/goods")
public class AdminGoodsController {

    @Autowired
    private DtsGoodsService dtsGoodsService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private DtsBrandService dtsBrandService;

    @Autowired
    private DtsCategoryService dtsCategoryService;

    /**
     * http://localhost:8083/admin/goods/list?page=1&limit=20&sort=add_time&order=desc
     * GET /admin/goods/list
     *
     * @param goodsSn
     * @param name
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
//    @RequiresPermissions("admin:goods:list")
//    @RequiresPermissionsDesc(menu = { "商品管理", "商品列表" }, button = "查询")
//    @GetMapping("/list")
//    public Object list(String goodsSn, String name,
//                       @RequestParam(defaultValue = "1") Integer page,
//                       @RequestParam(defaultValue = "10") Integer limit,
//                       @RequestParam(defaultValue = "add_time") String sort,
//                       @RequestParam(defaultValue = "desc") String order) {
//
//        IPage<DtsGoods> iPage = adminGoodsService.findListByQuery(goodsSn,name,page,limit,sort,order);
//
//        Map data = new HashMap<>();
//        data.put("total",iPage.getTotal());
//        data.put("items",iPage.getRecords());
//        return ResponseUtil.ok(data);
//    }
    @RequiresPermissions(value = "admin:goods:list")
    @RequiresPermissionsDesc(menu = {"商品管理", "商品列表"}, button = "查询")
    @GetMapping("/list")
    public Object list(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "20") Integer limit,
                       String name, String goodsSn, String sort, String order) {
        //获取当前用户拥有的角色id
        Integer[] roleIds = AuthSupport.currentUser().getRoleIds();
        //判断角色名字
        if (roleIds.length == 0 || roleIds == null) {
            return ResponseUtil.fail(-1, "没有相应权限");
        }
        //通过角色id获取身份
        Set<String> nameSet = roleService.queryByIds(roleIds);
        IPage<DtsGoods> goodsIPage;
        List<Integer> brandIds = null;
        if (!nameSet.contains("超级管理员")) {
            //根据用户的id查询对应的brand
            List<DtsBrand> brandList = dtsBrandService.findIdByAdminId(AuthSupport.currentUser().getId());
            brandIds = brandList.stream().map(DtsBrand::getId).collect(Collectors.toList());
        }
        goodsIPage = dtsGoodsService.findAllByPage(page, limit, name, goodsSn, sort, order, brandIds);
        //根据id查询所拥有的店铺
        Map data = new HashMap();
        data.put("total", goodsIPage.getTotal());
        data.put("items", goodsIPage.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * 跳转添加页面，查询catAndBrand信息
     * http://localhost:8080/admin/goods/catAndBrand
     */
    @GetMapping("/catAndBrand")
    public Object catAndBrand() {
        return getCatAndBrand();
    }

    /**
     * 添加和商品上架
     * http://localhost:8083/admin/goods/create
     */
    @RequiresPermissions(value = "admin:goods:create")
    @RequiresPermissionsDesc(menu = {"商品管理", "商品列表"}, button = "商品上架")
    @PostMapping("/create")
    public Object create(@RequestBody GoodsAllinone goodsAllinone) {
            dtsGoodsService.create(goodsAllinone);
        return ResponseUtil.ok();
    }

    /**
     * 修改商品信息的回调数据
     * http://localhost:8083/admin/goods/detail?id=23858
     */
    @RequiresPermissions(value = "admin:goods:detail")
    @RequiresPermissionsDesc(menu = {"商品管理", "商品列表"}, button = "编辑")
    @GetMapping("/detail")
    public Object detail(Integer id) {

        Map data = dtsGoodsService.detail(id);
        if (CollectionUtils.isEmpty(data)) {
            return ResponseUtil.fail(-1, "查询该商品信息失败");
        }
        return ResponseUtil.ok(data);
    }

    /**
     * 更新商品
     * http://localhost:8080/admin/goods/update
     *
     * @return
     */
    @RequiresPermissions(value = "admin:goods:update")
    @RequiresPermissionsDesc(menu = {"商品管理", "商品列表"}, button = "更新商品")
    @PostMapping("/update")
    public Object update(@RequestBody GoodsAllinone goodsAllinone) {

        try {
            dtsGoodsService.update(goodsAllinone);
        } catch (Exception e) {
            return ResponseUtil.fail(-1, e.getMessage());
        }

        return ResponseUtil.ok();
    }


    /**
     * 删除
     * http://localhost:8080/admin/goods/delete
     *
     * @return
     */
    @RequiresPermissions(value = "admin:goods:delete")
    @RequiresPermissionsDesc(menu = {"商品管理", "商品列表"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody DtsGoods goods) {
        if (goods.getId() == null) {
            return ResponseUtil.badArgument();
        }
        dtsGoodsService.delete(goods);
        return ResponseUtil.ok();
    }

    //获取类目和品牌商信息
    private Object getCatAndBrand() {
        //1.1查询类目信息
        List<DtsCategory> dtsCategories = dtsCategoryService.findCategoryByPid(0);
        //封装到CatVo对象中
        List<CatVo> categoryList = dtsCategories.stream().map(dtsCategory -> {
            CatVo catVo = new CatVo();
            catVo.setValue(dtsCategory.getId());
            catVo.setLabel(dtsCategory.getName());
            return catVo;
        }).collect(Collectors.toList());
        //循环查询子类目
        categoryList = categoryList.stream().map(category -> {
            List<DtsCategory> childrenCategoryList = dtsCategoryService.findCategoryByPid(category.getValue());
            List<CatVo> childrenVo = childrenCategoryList.stream().map(c -> {
                CatVo catVo = new CatVo();
                catVo.setValue(c.getId());
                catVo.setLabel(c.getName());
                return catVo;
            }).collect(Collectors.toList());
            category.setChildren(childrenVo);
            return category;
        }).collect(Collectors.toList());

        //查询品牌商信息
        //获取当前用户拥有的角色id
        Integer[] roleIds = AuthSupport.currentUser().getRoleIds();
        //判断角色名字
        if (roleIds.length == 0 || roleIds == null) {
            return ResponseUtil.fail(-1, "没有相应权限");
        }
        //通过角色id获取身份
        List<DtsBrand> list = new ArrayList<>();
        Set<String> nameSet = roleService.queryByIds(roleIds);
        if (!nameSet.contains("超级管理员")) {
            //根据用户的id查询对应的brand
            list = dtsBrandService.findBrandByAdminId(AuthSupport.currentUser().getId());
        } else {
            list = dtsBrandService.findBrandByAdminId(null);
        }
        List<CatVo> brandList = list.stream().map(dtsBrand -> {
            CatVo catVo = new CatVo();
            catVo.setValue(dtsBrand.getId());
            catVo.setLabel(dtsBrand.getName());
            return catVo;
        }).collect(Collectors.toList());


        Map<String, Object> data = new HashMap<>();
        data.put("categoryList", categoryList);
        data.put("brandList", brandList);
        return ResponseUtil.ok(data);
    }
}
